package com.xlh.openai.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xlh.openai.dao.OrderDao;
import com.xlh.openai.entity.OrderEntity;
import com.xlh.openai.entity.ProductEntity;
import com.xlh.openai.entity.enums.ExpireStatus;
import com.xlh.openai.entity.enums.PayStatus;
import com.xlh.openai.exception.ServiceException;
import com.xlh.openai.listener.OrderListener;
import com.xlh.openai.service.OrderService;
import com.xlh.openai.service.ProductService;
import com.xlh.openai.service.WechatUserService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private WechatUserService wechatUserService;

    @Autowired
    private ProductService productService;

    @Autowired
    private OrderListener orderListener;

    @Lazy
    @Autowired
    private WxMpService wxMpService;

    @Override
    public OrderEntity createOrder(ProductEntity productEntity, Integer userId) {

        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setProductId(productEntity.getId());
        orderEntity.setOutTradeNo(IdUtil.getSnowflakeNextIdStr());
        orderEntity.setQuantity(1);
        orderEntity.setTotalPrice(productEntity.getPrice());
        orderEntity.setUserId(userId);
        orderEntity.setProductInfo(JSONUtil.toJsonStr(productEntity));
        orderEntity.setTimeExpire(DateUtil.offsetMinute(new Date(), 10));
        save(orderEntity);
        // 订单数量递减
        productService.decrease(productEntity.getId(), productEntity.getStock());
        // 订单十分钟过期
        orderListener.addQueue(orderEntity);
        return orderEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void paySuccessByNumber(String outTradeNo) {

        OrderEntity orderEntity = null;
        try {
            orderEntity = getByOutTradeNo(outTradeNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(orderEntity == null){
            throw new ServiceException(" 未查询到当前订单！ ");
        }
        // 已支付
        if(orderEntity.getPayStatus().equals(PayStatus.PAY.getCode())){
            return;
        }

        String productInfo = orderEntity.getProductInfo();
        ProductEntity productEntity = JSONUtil.toBean(productInfo, ProductEntity.class);
        // 执行对当前用户次数的变更
        Integer sku = productEntity.getSku();
        // 执行插入当前用户增长条数中
        String openId = wechatUserService.addQuestionTime(orderEntity.getUserId(), sku);
        // 更改订单状态
        UpdateWrapper<OrderEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(OrderEntity::getPayStatus,PayStatus.PAY.getCode())
                .eq(OrderEntity::getId, orderEntity.getId());
        update(updateWrapper);
        sendTempToUser(orderEntity, openId);
    }


    /**
     * 发送订单回调成功的模板消息给用户
     * @param orderEntity
     * @param openId
     */
    private void sendTempToUser(OrderEntity orderEntity, String openId) {
        // 发送支付成功通知给用户
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .templateId("ihetAnG2QKPRyOXovKoGRaK1vo7xeVfUK-Q9fLCot_8")
                .build();
        templateMessage.addData(new WxMpTemplateData("first","您好，您的订单已支付成功！","#000000"));
        templateMessage.addData(new WxMpTemplateData("keyword1", String.valueOf(orderEntity.getTotalPrice()),"#000080"));
        templateMessage.addData(new WxMpTemplateData("keyword2","线上交易"));
        templateMessage.addData(new WxMpTemplateData("keyword3",DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss")));
        templateMessage.addData(new WxMpTemplateData("keyword4","线上交易"));
        templateMessage.addData(new WxMpTemplateData("remark","感谢您使用的同时也希望您提出宝贵的意见和建议！"));

        try {
            wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            log.error("发送模板信息异常！", e);
            throw new ServiceException("发送模板信息异常！");
        }
    }


    @Override
    public List<OrderEntity> listNotExpireOrders() {

        QueryWrapper<OrderEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(OrderEntity::getPayStatus, PayStatus.NOT_PAY.getCode())
                .eq(OrderEntity::getIsExpire, ExpireStatus.NOT_PAY.getCode());
        return list(queryWrapper);
    }

    /**
     * 根据交易流水号查询订单
     * @param outTradeNo
     * @return
     */
    private OrderEntity getByOutTradeNo(String outTradeNo) {

        QueryWrapper<OrderEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(OrderEntity::getOutTradeNo, outTradeNo);
        return getOne(queryWrapper);
    }


}